<template>
  <div class="inputWrapper">
    <input
      :placeholder="placeholder"
      :class="{ success: state === 'success', error: state === 'fail' }"
      v-model="inputVal"
      @input="handleInput"
      @change="checkVal"
    />
  </div>
</template>

<script>
// blur      是失去焦点就会触发
// change    值被修改过并失去焦点的时候触发
export default {
  //子组件通过props接收父组件传递过来的属性值
  props: ["placeholder", "rule", "err_message"],
  data() {
    return {
      inputVal: "",
      state: "",
    };
  },
  //侦听器
  watch: {
    inputVal(val) {
      // console.log(val)
      // console.log(typeof(this.rule))
      if (!this.rule.test(val)) {
        this.state = "fail";
      } else {
        this.state = "success";
      }
    },
  },
  methods: {
    //获取到input框的值
    handleInput(data) {
      // console.log(this.inputVal,this.$attrs.type)
      console.log("this.$attrs.name", this.$attrs.name);
      // 子传父 使用this.$emit(自定义事件，要传递数据)
      this.$emit("input", { [this.$attrs.name]: this.inputVal });
    },
    checkVal() {
      if (this.state === "fail") {
        this.$toast.fail("用户名或密码不能为空");
      }
    },
  },
};
</script>

<style lang="less">
.inputWrapper {
  padding-bottom: 16/360 * 100vw;
  input {
    width: 100%;
    height: 48/360 * 100vw;
    line-height: 48/360 * 100vw;
    font-size: 18/360 * 100vw;
    border: none;
    outline: none;
    border-bottom: 1px solid #333;
  }
  .success {
    border-bottom-color: green;
  }
  .error {
    border-bottom-color: red;
  }
}
</style>
